/*
 * @Author: yangzonglong
 * @Date: 2021-02-22 13:56:10
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-06-30 14:25:13
 * @Auditor: 
 */
import React, { useEffect, useState, useRef } from 'react';
import { Modal, Form, Select } from 'antd';
import { Table, units } from '@library';
import { TableRefProps } from '@library/components/table/interface';
import { createRandomStr } from './../../../util';

interface SourceProps {
  filedCode: string;
  type: string;
  name: string;
  id: string;
}

interface Props {
  visible: boolean;
  onErr: () => void;
  onCancel: () => void;
  onOk: (options: any, name: string) => void;
}

const columns = [
  {
    dataIndex: 'filedCode', title: '字段', width: 150, ellipsis: true,
    tooltip: true,
  },
  {
    dataIndex: 'name', width: 150, ellipsis: true,
    tooltip: true,
  },
  {
    dataIndex: 'type', width: 100, ellipsis: true,
    tooltip: true,
  },
  {
    dataIndex: 'comment', width: 200, ellipsis: true,
    tooltip: true,
  },
];

const actionBtnGroup = [
  {
    "text": "编辑",
    "type": "edit",
    "scriptText": "",
    "url": "",
    "key": "edit"
  },
  {
    "text": "删除",
    "type": "delete",
    "scriptText": "",
    "url": "",
    "key": "delete"
  }
];

const getSource = (v: any) => {
  const _keys = Object.keys(v);
  const _value = Object.values(v);

  return _value.map((item: any, index) => ({
    name: item.cn || item?.locales?.cn || _keys[index],
    id: _keys[index],
    index,
    filedCode: _keys[index],
    type: item.type,
    comment: item.comment
  })).sort((a, b) => (b.index - a.index));
};

const getTabFiledsSource = (v: any) => {

  const _value = getSource(v).filter((item: any) => !!item.comment);

  let arr: any[] = [];

  _value.forEach((item: any) => {
    try {
      const v = JSON.parse(item.comment);
      if (typeof v === 'object') {
        arr.push({
          filedCode: item.filedCode,
          id: item.id,
          comment: v,
        });
      }
    } catch (error) {

    }
  });
  return arr;
};

const ModelTable = ({ visible, onOk, onCancel, onErr }: Props) => {

  const tableRef = useRef<TableRefProps>(null);
  const [value, setValue] = useState('');
  const [tabValue, setTabValue] = useState('');
  const [modelSource, setModelSource] = useState<string[]>([]);
  const [tabFileds, setTabFileds] = useState<any[]>([]);
  const [dataSource, setDataSource] = useState<SourceProps[]>([]);

  useEffect(() => {
    units.serverLoading('/bk/api/lowcode/getModels', {}).then(res => {
      setModelSource(res.models || []);
    });
  }, []);

  useEffect(() => {
    if (value) {
      tableRef.current?.onRefresh();
      units.serverLoading(`/bk/api/lowcode/${value}/getModel`, {}).then(res => {
        setDataSource(getSource(res.attributes || {}));
        setTabFileds(getTabFiledsSource(res.attributes || {}));
      });
    }
  }, [value]);

  const _onOK = () => {

    if (!value) return;

    setTabValue('');
    setDataSource([]);
    setTabFileds([]);

    const rows = tableRef.current?.getSelectedRows();

    if (tabValue) {

      const _ = tabFileds.find(item => item.filedCode === tabValue);
      const keys = Object.keys(_.comment);
      const values = Object.values(_.comment);
      if (keys.length === values.length && keys.length) {
        const options = {
          type: "dataList",
          id: createRandomStr('dataList'),
          parentId: "",
          options: {
            actionBtnGroup,
            name: "list",
            showTabs: true,
            tabsOption: keys?.map((item, index) => ({
              id: Math.random().toString(36).substring(2),
              lable: values[index],
              jumpNewPage: true,
              value: item,
              url: `/bk/api/lowcode/${value}/find`,
              query: `{"where":{"${_.filedCode}":"${item}"}}`,
              columns: rows?.map(item => ({
                "title": item.name,
                "dataIndex": item.filedCode,
                "key": Math.random().toString(36).substring(2),
                "id": item.filedCode,
                "checked": true
              })),
              actionBtnGroup,
              // addUrl: `/bk/api/lowcode/${value}/add`,
              showRowSelection: false
            }))
          }
        };
        onOk(options, value);
      } else {
        onErr();
        units.message.error('备注字段错误,无法生成');
      }

    } else {
      const options = {
        type: "dataList",
        id: createRandomStr('dataList'),
        parentId: "",
        options: {
          name: "list",
          actionBtnGroup,
          url: `/bk/api/lowcode/${value}/find`,
          query: "",
          addUrl: `/bk/api/lowcode/${value}/add`,
          columns: rows?.map(item => ({
            "title": item.name,
            "dataIndex": item.filedCode,
            "key": Math.random().toString(36).substring(2),
            "id": item.filedCode,
            "checked": true
          })),
          jumpNewPage: true,
          treeStructure: false
        }
      };
      onOk(options, value);
    }
    setValue('');
  };
  const _onCancel = () => {
    setValue('');
    setTabValue('');
    setDataSource([]);
    setTabFileds([]);
    onCancel();
  };

  return (
    <Modal destroyOnClose visible={visible} title='模型列表' width={600} onOk={_onOK} onCancel={_onCancel}>
      <Form>
        <Form.Item label='选择模型'>
          <Select
            value={value}
            onChange={setValue}>
            {modelSource.map(item => (
              <Select.Option key={item} value={item}>{item}</Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item label='Tab字段'>
          <Select
            allowClear
            value={tabValue}
            onChange={setTabValue}>
            {tabFileds.map(item => (
              <Select.Option key={item.filedCode} value={item.filedCode}>{item.filedCode}</Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
      <div style={{ flexDirection: 'column', display: 'flex', maxHeight: '600px', overflow: 'auto' }}>
        <Table ref={tableRef} rowSelectionType='checkbox' flat dataSource={dataSource} columns={columns} />
      </div>

    </Modal>
  );
};

export default ModelTable;